(*
	recvChars(count) -- Return count characters from the serial port.

	To compile and link this file using Macintosh Programmer's Workshop,

		pascal -w recvChars.p
		link -m ENTRYPOINT -o HyperCommands -rt XFCN=7031 -sn Main=recvChars ¶
			recvChars.p.o "{MPW}"Libraries:interface.o

	© Copyright 1987,88 by Apple Computer, Inc.

	Initial coding 9/87 by Harry R. Chesley.
*)

{$R-}

{$S recvChars } 	{ Segment name must be the same as the command name. }

unit DummyUnit;

interface

uses MemTypes, QuickDraw, OSIntf, HyperXCmd;

procedure EntryPoint(paramPtr: XCmdPtr);
	
implementation

type

Str31 = String[31];

procedure recvChars(paramPtr: XCmdPtr); forward;

procedure EntryPoint(paramPtr: XCmdPtr);

	begin
		recvChars(paramPtr);
	end;

procedure recvChars(paramPtr: XCmdPtr);

	var readCount: longInt;
		readCountStr: Str255;
		l: longInt;
		p: Ptr;

	{$I XCmdGlue.inc}

	procedure Fail(errMsg: Str255); { set theResult and quit }
		begin
			paramPtr^.returnValue := PasToZero(errMsg);
			exit(recvChars);
		end;

	{$I SPortUtil.inc}

	begin
		if paramPtr^.paramCount <> 1 then Fail('parameter count is not 1');

		ZeroToPas(paramPtr^.params[1]^,readCountStr);		{ First parameter is count to read. }
		readCount := StrToNum(readCountStr);
		if readCount < 0 then Fail('invalid count');

		SetUpSPortGlobals;
		EnsureOpenPort;

		{ Create the input handle. }
		paramPtr^.returnValue := NewHandle(readCount+1);
		HLock(paramPtr^.returnValue);
		{ Read, read, read... }
		if readCount > 0 then
			begin
				l := readCount;
				if FSRead(ThisSPort.portInDev,l,paramPtr^.returnValue^) <> noErr then
					begin
						DisposHandle(paramPtr^.returnValue);
						Fail('FSRead failed');
					end;
				{ Shrink the handle if we didn't get everything (paranoid programing; this should be impossible). }
				if l <> readCount then SetHandleSize(paramPtr^.returnValue,l+1);
			end
		else l := 0;
		{ Tack on a zero termination byte. }
		p := ptr(ord4(paramPtr^.returnValue^)+l);
		p^ := 0;
		{ Should we strip? }
		if ThisSPort.stripIncoming then
			begin
				{ If so, rip dem bits off. }
				p := paramPtr^.returnValue^;
				while p^ <> 0 do
					begin
						p^ := BAND(p^,$7F);
						p := pointer(ord4(p)+1);
					end;
			end;
		HUnlock(paramPtr^.returnValue);
	end;

end.
